// pages/list/list.js
const app = getApp();
var funcs = require('../../../static/js/funcs.js');
// import { networkList } from '../../static/js/network';
import {
  cities,
  areas
} from '../../../static/js/city';
const loc = "../../../static/images/scrcu_green.png";
const search = "../../../static/images/search.png";
const nores = "../../../static/images/nores.png";
const phone_ioc = "../../../static/images/phone.png";
// const mysql = require('mysql');
var funcs2 = require('../../../static/js/func2.js');

const atm = "../../../static/images/ATM_before.png";
const selected_atm = "../../../static/images/ATM_after.png";
const navi_loc = "../../../static/images/loc@.png";
const selected_loc = "../../../static/images/scrcu_blue.png";
const offline_loc = "../../../static/images/scrcu_off.png";
const search_city = "../../../static/images/loc_not.png";

Page({
  /*
    页面的初始数据
   */
  data: {
    jigou_type: 1,
    display_flag: true,
    shaixuan_toggle: 0,
    shaixuan_select: [0, 0, 0, 0, 0, 0],
    icon_type: 0,
    search_city,
    offline_loc,
    navi_loc,
    shaixuan_item: ['个人贷款', '社保', '公积金', '税务服务', '快递驿站', '存款办理'],
    category_list: ['列表查询','地图查询'],
    select_category:0,
    nearmapid: "",
    curr_city:"",
    first_load: true,
    phone_ioc,
    loc,
    nores,
    search,
    cities,
    areas,
    city: "",
    area: "",
    maps_info: [],
    show_flag: false,
    objectMultiArray: [cities, areas[0]],
    multiIndex: [0, 0],
    networkList: [],
    upper: 4,
    lower: 1,
    Isbottom: false,
    limit_size: 5,
    liked: false
  },
  select_category:function(e){
    let index = e.currentTarget.dataset.category
    console.log(index)
    let that = this
    this.setData({
      select_category: index
    })

    if(index==1){
      this.judgeTime()
      let _this = this;
      let mylatitude = app.globalData.latitude;
      let mylongitude = app.globalData.longitude;
      funcs2.getAddressByKey(mylatitude, mylongitude).then(res => {
        // console.log(res.data.result.ad_info.district)
        let areaname = res.data.result.ad_info.district
        let cityname = res.data.result.ad_info.city;
        _this.setData({
          city_name: cityname,
          area_name: areaname
        })
        _this.reloadDataByCityName(cityname,areaname,true)
      })
    }
  },
  clickLikeTap:function(e){
    let that = this
    let openid = app.globalData.openid
    funcs2.adToFavor(this.data.nearmapid,openid).then(res=>{
      if(res.data.succeed){
        if(res.data.data=="添加收藏成功"){
          that.setData({
            liked:true
          })
          wx.showToast({
            title: "添加关注成功",
            icon: 'none',
            duration: 2000
          })
        }else{
          that.setData({
            liked:false
          })
          wx.showToast({
            title: "取消关注成功",
            icon: 'none',
            duration: 2000
          })
        }
      }else{
        wx.showToast({
          title: "请先登录",
          icon: 'error',
          duration: 2000
        })
        console.log("请先登录")
        // wx.reLaunch({
        //   url: '/pages/my/my',
        // })
      }
    })
  
  },
  judgeTime: function () {
    let now = new Date();
    // 获取当前时间的小时
    let hour = now.getHours();
    let mini = now.getMinutes();
    console.log("当前时间：" + hour + ":" + mini)
    if (9 <= hour && hour < 18) {
      if (hour == 17 && mini > 30) {
        this.setData({
          open_flag: false
        })
      } else {
        this.setData({
          open_flag: true
        })
      }
    } else {
      this.setData({
        open_flag: false
      })
    }
  },

  clickMe: function () {
    this.setData({
      msg: "Hello World"
    })
  },

  pre_login: function (res) {
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          //发起网络请求console.log
          app.globalData.code = res.code;
          resolve(res)
        },
        fail(res) {
          reject(res);
        }
      })
    })
  },
  jumptomapForMap: function (res) {
    let data = res.currentTarget.dataset

    let longitude = data.longitude;
    let latitude = data.latitude;

    console.log(latitude + latitude + data.nam + data.address)
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name: data.name,
      address: data.address
    })
  },
  jumptomap: function (res) {
    // console.log("here")
    // console.log(res.currentTarget.dataset)
    let data = res.currentTarget.dataset

    let longitude = data.longitude;
    let latitude = data.latitude;
    let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    let x = longitude - 0.0065;
    let y = latitude - 0.006;
    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    let wz = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    let lon = z * Math.cos(wz);
    let lat = z * Math.sin(wz);
    longitude = lon;
    latitude = lat;
    console.log(latitude + latitude + data.nam + data.address)
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name: data.name,
      address: data.address
    })
  },

  call_phone: function (res) {
    let data = res.currentTarget.dataset
    wx.showModal({
      title: "提示",
      content: "拨打 " + data.telephone + " ?",
      complete: (res) => {
        if (res.cancel) {
          return
        }
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: data.telephone,
            success: function () {
              console.log("拨打电话成功！")
            },
            fail: function () {
              console.log("拨打电话失败！")
            }
          })
        }
      }
    })
  },
  clickMe2: function () {
    this.setData({
      msg: ""
    })
  },

    //city选择
    bindCityChangeForMap(event) {
      this.judgeTime()
      console.log('picker发送选择改变，携带值为', event.detail.value)
      let city_index = event.detail.value[0];
      let area_index = event.detail.value[1];
      let city = this.data.cities[city_index].name;
      let area = this.data.objectMultiArray[1][area_index].name;
      this.setData({
          city_name:city,
          area_name:area
      })
      console.log(city + ":" + area)
      this.reloadDataByCityName(city,area,true)
    },
  //city选择
  bindCityChange(event) {
    console.log('picker发送选择改变，携带值为', event.detail.value)
    let city_index = event.detail.value[0];
    let area_index = event.detail.value[1];
    let city = this.data.cities[city_index].name;
    let area = this.data.objectMultiArray[1][area_index].name;

    funcs2.getInstDatabyName(city).then(res => {
      // console.log(res.data);
      let real_networkList = []
      let networkList = res.data.data;
      networkList.map((item, index) => {
        if (item.telephone != null && item.telephone.length > 0)
          real_networkList.push(item);
      })
      this.setData({
        networkList: real_networkList
      })
      this.getMyLocation(real_networkList)
    }).then(() => {
      this.setData({
        city: city,
        area: area,
        city_area: city + '-' + area
      })
      console.log(this.data.city)
      console.log(this.data.area)
      this.searchContext("")
    })

  },
  //city切换
  bindColumnCityChange(event) {
    console.log('修改的列为', event.detail.column, '，值为', event.detail.value);
    switch (event.detail.column) {
      case 0: //修改第一列
        let arr = this.data.multiIndex;
        arr[0] = event.detail.value;
        arr[1] = 0;
        this.setData({
          objectMultiArray: [cities, areas[event.detail.value]],
          multiIndex: arr,
        })
        break;
      case 1: //修改第二列
        let arr2 = this.data.multiIndex;
        arr2[1] = event.detail.value;
        // console.log(arr2)
        this.setData({
          multiIndex: arr2,
        })
        break;
    }
    // console.log(this.data.multiIndex)
  },

  //area选择
  bindAreaChange(event) {
    let index = event.detail.value;
    let area = this.data.cities[index].name;
    this.setData({
      area: area
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */

  //重新计算当前位置和所在的城市网点
  reload: function () {
    let _this = this;
    let that = this
    this.judgeTime()
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success(res) {
        let latitude = res.latitude
        let longitude = res.longitude

        funcs2.getAddressByKey(latitude, longitude).then(res => {
          let register_location = res.data.result.ad_info.name
          funcs2.judgeUser(app.globalData.openid,register_location).then(res=>{
            if(res.data.succeed){
              if(res.data.data.successcode=="0000"){
                app.globalData.loginFlag = false;
                console.log("未登记用户")
              }else{
                console.log("已登记用户> "+res.data.data.userinfo)
                app.globalData.loginFlag = true;
                that.setData({
                  userinfo:res.data.data.userinfo
                })
              }
            }
          })

          let cityname = res.data.result.ad_info.city;
          console.log("当前城市为："+cityname)
          _this.setData({
            curr_city:cityname
          })
          funcs2.getInstDatabyName(cityname).then(res => {
            let real_networkList = []
            let networkList = res.data.data;
            if (networkList.length === 0) {
              wx.showToast({
                title: "该省份城市无网点信息\r\n已为你自动定位到成都",
                icon: 'none',
                duration: 4000
              })

              funcs2.getInstDatabyName("成都市").then(res => {
                networkList = res.data.data
                networkList.map((item, index) => {
                  if (item.telephone.length > 0)
                    real_networkList.push(item);
                })
                _this.setData({
                  networkList: real_networkList
                })
                _this.getMyLocation(real_networkList)
              })
            } else {
              networkList.map((item, index) => {
                if (item.telephone.length > 0)
                  real_networkList.push(item);
              })
              _this.setData({
                networkList: real_networkList
              })
              _this.getMyLocation(real_networkList)
            }
          })
        })
      }
    })
  },

  onLoad(options) {
    let openid = app.globalData.openid
    console.log("生命周期函数--监听页面加载")
    let that = this
    funcs.judgeStaff(openid).then(res=>{
      if(res.data.succeed){
        let area = res.data.data.area
        let city = res.data.data.city
        funcs2.getInstDatabyName(city).then(res => {
          // console.log(res.data);
          let real_networkList = []
          let networkList = res.data.data;
          networkList.map((item, index) => {
            if (item.telephone != null && item.telephone.length > 0)
              real_networkList.push(item);
          })
          that.setData({
            networkList: real_networkList
          })
          that.getMyLocation(real_networkList)
        }).then(() => {
          that.setData({
            city: city,
            area: area,
            city_area: city + '-' + area
          })
          console.log(this.data.city)
          console.log(this.data.area)
          that.searchContext("")
        })
      }
    })
    
  },

  getMyLocation: function (inputList) {
    // return;
    return new Promise((resolve, reject) => {
      var _this = this;
      wx.getLocation({
        type: "gcj02",
        fail(res){
          console.log("获取位置信息失败")
          console.log(res)
        },
        success(res) {
          const latitude = res.latitude;
          const longitude = res.longitude;
          app.globalData.latitude = latitude;
          app.globalData.longitude = longitude;
          let sortList = [];
          console.log("获取位置信息成功")
          inputList.map((item, index) => {
            let distance = funcs2.getDistance2(latitude, longitude, item.latitude, item.longitude);
            item.distance = distance;
            // if(item.address.search("成都市新都区大丰")!=-1)
            //   console.log("有成都")
            sortList.push(item);
          })
          //距离排序（最近优先）
          sortList.sort((item1, item2) => {
            return item1.distance - item2.distance
          })
          wx.hideLoading();
          _this.setData({
            maps_info: sortList,
            show_flag: sortList.length
          })
          resolve(sortList);
        }
        
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log("页面初次渲染完成")
  },

  onInput: function (e) {
    let onInput = e.detail.value
    console.log(e.detail.value)
    // this.searchContext(onInput)
    this.searchContext2(onInput)
  },
  /**
   * 生命周期函数--监听页面显示
   */

  onCurSearch(input_list, input) {
    var _this = this;
    let new_networklist = [];
    input_list.map((item, index) => {
      let name = item.name
      let address = item.address
      if (name.search(input) != -1&&item.telephone!=null&&item.telephone.length!=0&&item.latitude!=null&&item.longitude!=null&&item.latitude.length!=0&&item.longitude.lengt!=0) {
        new_networklist.push(item);
      } else if (address.search(input) != -1&&item.telephone!=null&&item.telephone.length!=0&&item.latitude!=null&&item.longitude!=null&&item.latitude.length!=0&&item.longitude.lengt!=0) {
        new_networklist.push(item);
      }
    })
    // for input in networkList.name
    if (new_networklist.length > 0)
      _this.setData({
        show_flag: true,
      })
    if (new_networklist.length <= 0)
      _this.setData({
        show_flag: false,
      })
    return new_networklist
  },

  filter_list(city, area) {
    let temp_networklist = []
    console.log("filter_list" + city + area)
    this.data.networkList.map((item, index) => {
      let address = item.address
      // console.log(address)
      if (address.search(area) != -1)
        temp_networklist.push(item);
      else if (address.search(area.slice(0, -1)) != -1) {
        console.log("修剪后的area为" + area.slice(0, -1))
        temp_networklist.push(item);
      }
    })
    // console.log("return"+temp_networklist)
    return temp_networklist
  },

  searchContext(input) {
    let input_networkList = this.data.networkList
    console.log(input_networkList)
    if (this.data.city.length != 0 | this.data.area.length != 0) {
      input_networkList = this.filter_list(this.data.city, this.data.area)
    }
    // console.log("用于检索的："+input_networkList)
    let new_networklist = this.onCurSearch(input_networkList, input)
    // console.log("完成搜索后的："+new_networklist)
    this.getMyLocation(new_networklist)
    this.setData({
      limit_size: 5
    })
    // new_networklist
  },

  searchContext2: function(input){
    let input_networkList = []
    let _this = this
    // wx.showLoading({
    //   title: '加载中...',
    //   mask: true
    // });
    if(input.length>0){
      funcs2.getAllData().then(res=>{
        input_networkList = res.data.data
        console.log(input_networkList)
        let res_list = this.onCurSearch(input_networkList, input)
        console.log(res_list)
        _this.getMyLocation(res_list)
        _this.setData({
          limit_size: 5
        })
        // wx.hideLoading()
      })
    }else{
      console.log(_this.data.curr_city)
      funcs2.getInstDatabyName(_this.data.curr_city).then(res => {
        let networkList = res.data.data
        let real_networkList = []
        networkList.map((item, index) => {
          if (item.telephone.length > 0)
            real_networkList.push(item);
        })
        _this.setData({
          networkList: real_networkList
        })
        _this.getMyLocation(real_networkList)
        // wx.hideLoading()
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    this.getMyLocation(this.data.networkList)
    this.setData({
      city: "全部",
      area: "全部",
      city_area: "全部" + '-' + "全部",
      upper: 4,
      lower: 1,
      Isbottom: false,
      limit_size: 5
    })
    this.reload()
    wx.stopPullDownRefresh();
    setTimeout(() => {
      wx.hideNavigationBarLoading();
    }, 2000);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onShow(){
    let that = this
    console.log("onshow页面监听")

  },
  upperFunction() {
    console.log("upperFunction")
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log("达到最下面")
    console.log("this.data.limit_size:" + this.data.limit_size)
    console.log("this.data.maps_info.length:" + this.data.maps_info.length)
    if (this.data.limit_size <= this.data.maps_info.length) {
      let temp_num = this.data.limit_size;
      this.setData({
        limit_size: temp_num + 5
      })

      wx.showLoading({
        title: '加载中...',
        mask: true
      });
      setTimeout(() => {
        wx.hideLoading()
      }, 600)

    } else {
      this.setData({
        Isbottom: true
      })
    }
  },

  junmToHome: function (res) {
    let data = res.currentTarget.dataset;
    console.log(data)
    var jsonString = JSON.stringify(data);
    //跳转页面并传递json字符串
    wx.navigateTo({
      url: '/pages/home/home?params=' + encodeURIComponent(jsonString)
    })
  },
  errorNotice: function (res) {
    wx.showToast({
      title: "因数据安全考虑\r\n目前暂不开放该功能",
      icon: 'none',
      duration: 2000
    })
  },

  reloadDataByCityName: function (cityname, areaname, switchFlag) {
    console.log("reloadDataByCityName"+cityname + ":" + areaname)
    let _this = this;
    var tempMarkers = [];
    var targetMarkers = [];
    let mylatitude = app.globalData.latitude;
    let mylongitude = app.globalData.longitude;

    _this.getDataFilterByName(cityname).then(res => {
      // console.log(res.data);
      let networkList = res.data.data;
      // console.log(res.data)
      
      let id = 0;
      networkList.forEach((m, index) => {
        var info = {
          id: 0,
          iconPath: this.data.jigou_type==1?this.data.loc:atm,
          latitude: 0.0, // 每一个被标点的纬度
          longitude: 0.0, // 每一个被标点的经度
          width: 25, // 使用图标的宽度
          height: 25, // 使用图标的高度
          name: "", // 点击标记点显示的title
          address: "",
          title:"",
          telephone: ""
        };
        // info.id = index;
        let longitude = Number(m.longitude);
        let latitude = Number(m.latitude);
        let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        let x = longitude - 0.0065;
        let y = latitude - 0.006;
        let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi)
        let wz = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        let lon = z * Math.cos(wz);
        let lat = z * Math.sin(wz);
        longitude = lon;
        latitude = lat;
        info.latitude = latitude;
        info.longitude = longitude;
        info.name = m.name;
        info.address = m.address
        info.telephone = m.telephone
        info.title = m.name;
        
        // console.log(info)
        if (m.telephone != null && m.telephone.length > 0){
          targetMarkers.push(info)
          if (m.address.search(areaname) != -1) {
            info.id = id;
            id++;
            tempMarkers.push(info)
          } else if (m.address.search(areaname.slice(0, -1)) != -1) {
              info.id = id;
              id++;
              console.log("修剪后的area为" + areaname.slice(0, -1))
              tempMarkers.push(info)
          }
        }
      })
      console.log(tempMarkers)

      let new_cnt = _this.data.fst_cnt + 1;
      _this.setData({
        fst_cnt:new_cnt
      })
      if(tempMarkers.length===0&&targetMarkers.length!=0&&new_cnt===1){
        let sortTargetList = [];
        targetMarkers.map((item, index) => {
          let distance = funcs2.getDistance(mylatitude, mylongitude, item.latitude, item.longitude);
          item.distance = distance;
          sortTargetList.push(item);
        })
        //距离排序（最近优先）
        sortTargetList.sort((item1, item2) => {
          return item1.distance - item2.distance
        })
        console.log(sortTargetList[0].latitude)
        console.log(sortTargetList[0].longitude)
        funcs.getAddressByKey(sortTargetList[0].latitude,
          sortTargetList[0].longitude).then(res=>{
          let new_area = res.data.result.ad_info.district
          _this.reloadDataByCityName(cityname,new_area,switchFlag)
          _this.setData({
            area_name: new_area
          })
          // console.log(res.data.result.ad_info.district)
        })
        return
      }

      let sortList = [];
      tempMarkers.map((item, index) => {
        let distance = funcs2.getDistance(mylatitude, mylongitude, item.latitude, item.longitude);
        item.distance = distance;
        sortList.push(item);
      })
      //距离排序（最近优先）
      sortList.sort((item1, item2) => {
        return item1.distance - item2.distance
      })

      _this.setData({
        networkList: sortList
      })

      if (sortList.length !== 0) {
        console.log("sortList.length")
        id = sortList[0].id;
        tempMarkers[id].iconPath = this.data.jigou_type==1?selected_loc:selected_atm;
        tempMarkers[id].width = 32;
        tempMarkers[id].height = 32;
        _this.setData({
          markers: tempMarkers,
          display_flag: true,
          last_selected_id: id,
          selected_name: sortList[0].name,
          selected_address: sortList[0].address,
          selected_latitude: sortList[0].latitude,
          selected_longitude: sortList[0].longitude,
          selected_telephone: sortList[0].telephone,
          selected_distance: sortList[0].distance
        })
        if(switchFlag==true){
          _this.setData({
            latitude: sortList[0].latitude,
            longitude: sortList[0].longitude
          })
        }
      } else {
        _this.setData({
          display_flag: false,
          markers: [],
          latitude: mylatitude,
          longitude: mylongitude
        })
      }
    }).then(res => {
    setTimeout(function () {
      wx.hideLoading()
    }, 1000)
    })
  },
  getDataFilterByName:function(cityname){
    return new Promise((resolve, reject) => {
        if(this.data.jigou_type==1){
          funcs2.getInstDatabyName(cityname).then(res=>{
            // console.log(res)
            resolve(res);
          })
        }else if(this.data.jigou_type==0){
          funcs2.getATMByCityName(cityname).then(res=>{
            resolve(res);
          })
        }
    });
  },
  jigou_type_event(event) {
    this.setData({
      jigou_type: this.data.jigou_type == 1 ? 0 : 1
    })
    this.reloadDataByCityName(this.data.city_name,this.data.area_name,false)
  },
  shaixuan_event(event) {
    this.setData({
      shaixuan_toggle: this.data.shaixuan_toggle == 1 ? 0 : 1
    })
  },
  shaixuan_type_event(event) {
    let index = event.currentTarget.dataset.index
    let shaixuan_select = this.data.shaixuan_select
    shaixuan_select[index] = shaixuan_select[index] == 1 ? 0 : 1;
    this.setData({
      shaixuan_select: shaixuan_select
    })
    console.log(shaixuan_select)
  },
  markerTap: function (option) {
    let id = option.detail.markerId
    console.log(option.detail.markerId)
    console.log(this.data.markers[id])
    let name = this.data.markers[id].name
    let latitude = this.data.markers[id].latitude
    let longitude = this.data.markers[id].longitude
    let address = this.data.markers[id].address
    let telephone = this.data.markers[id].telephone

    let mylatitude = app.globalData.latitude;
    let mylongitude = app.globalData.longitude;

    let distance = funcs2.getDistance(latitude, longitude, mylatitude, mylongitude);
    console.log(name + latitude + ":" + longitude + "  " + address + ":" + telephone + ":" + distance)
    
    let tempmarkers = this.data.markers;
    let last_id = this.data.last_selected_id;

    //地图机构图标点击动态修改
    if (last_id != null) {
      tempmarkers[last_id].iconPath = this.data.jigou_type==1?this.data.loc:atm;
      tempmarkers[last_id].width = 25;
      tempmarkers[last_id].height = 25;
    }
    tempmarkers[id].iconPath = this.data.jigou_type==1?selected_loc:selected_atm;
    tempmarkers[id].width = 32;
    tempmarkers[id].height = 32;

    console.log("打印测试" + tempmarkers[id].telephone)
    this.setData({
      display_flag: true,
      last_selected_id: id,
      markers: tempmarkers,
      selected_name: name,
      selected_address: address,
      selected_latitude: latitude,
      selected_longitude: longitude,
      selected_telephone: telephone,
      selected_distance: distance
    })

  },
})